package com.tianlh.service.exam;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 黑子
 * @Date 2018/2/6 21:51
 */
public class unsafeVolatile {
    //同时创建十个线程，每个线程自增100次
    //主程序等待3秒让所有线程全部运行完毕后输出最后的count值
    //使用volatile修饰计数变量count
    public static AtomicInteger count = new AtomicInteger(0);
    //public static volatile int count = 0;
    public static void main(String[] args){
        final unsafeVolatile data  = new unsafeVolatile();
        for(int i=0;i<10;i++){
            new Thread(
                () -> {
                    try{
                        Thread.sleep(1);
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                    for(int j=0;j<100;j++){
                        data.addCount();
                    }
                    System.out.print(count+" ");
                }
            ).start();
        }
        try{
            Thread.sleep(3000);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        System.out.println();
        System.out.print("count="+count);
    }
    public void addCount(){
        count.getAndIncrement();
        //count = count + 1;
        // count++; 不安全volatile不能保证原子性
    }
}
